//
//  SNOxDetailVc.m
//  project
//
//  Created by 黄建华 on 2017/12/12.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNOxDetailVc.h"
#import "SNOXChartView.h"
#import "SNOxDetailTableViewCell.h"
#define LEFTWIDTH 30.0
@interface SNOxDetailVc ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView         *headView;     //下拉视图
@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) SNOxChartView  *ChartView;
@property (nonatomic, assign) SelectDateType type;
@property (nonatomic, strong) UIView         *labelView;

@end

@implementation SNOxDetailVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initTabelView];
}

- (void)initTabelView {
    _tableView                = [[UITableView alloc]initWithFrame:CGRectMake(0, 70 +FitSimpleIpx(0, 20), HHHWIDTH, HHHHEIGHT - 70 -FitSimpleIpx(0, 20)) style:UITableViewStylePlain];
    _tableView.delegate       = self;
    _tableView.dataSource     = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _headView                  = [[UIView alloc] init];
    _headView.frame            = SNFRAME(0, 0, HHHWIDTH, _tableView.height *0.60);
    _tableView.tableHeaderView = _headView;
    
    _ChartView = [[SNOxChartView alloc] initWithFrame:SNFRAME(LEFTWIDTH, 0, HHHWIDTH - LEFTWIDTH, _headView.height *0.6)];
    [_headView addSubview:_ChartView];
    
    [self loadLabelValue];
    [self selectType:SelectDateDay];
    
    SNShadowView *lineView_1 = [[SNShadowView alloc] init];
    [lineView_1 showWithType:1];
    lineView_1.frame = SNFRAME(0, _labelView.origin.y +_labelView.height  - 25 + 25, HHHWIDTH, 3);
    [_headView addSubview:lineView_1];
    
    UIImageView *sleepImg = [[UIImageView alloc] init];
    sleepImg.frame = SNFRAME(5 + FitSimpleSize(0, 0, 10, 10, 10), lineView_1.origin.y+ FitSimpleSize(0, 0, 5, 5, 5), 60, 60);
    sleepImg.image = [UIImage imageNamed:@"血氧监测"];
    [_headView addSubview:sleepImg];
    
    UILabel *sleepTypeLabel = [[UILabel alloc] init];
    sleepTypeLabel.textAlignment = NSTextAlignmentLeft;
    sleepTypeLabel.frame         = SNFRAME(sleepImg.center.x + 30, sleepImg.center.y - 10, 120, 20);
    sleepTypeLabel.textColor     = SNCOLORBLACK;
    sleepTypeLabel.text          = SN_Text(@"血氧详情");
    sleepTypeLabel.font          = SNFONT(17.0);
    [_headView addSubview:sleepTypeLabel];
    
    //    UIView *red = [[SNShadowView alloc] init];
    //    red.frame = SNFRAME(0, 0, 15, 15);
    //    red.center = CGPointMake(sleepTypeLabel.x + 100 + FitSimpleSize(0, 20, 30, 35, 35), sleepTypeLabel.center.y);
    //    red.backgroundColor = SNHEARTBIG;
    //    red.layer.masksToBounds = YES;
    //    red.layer.cornerRadius = red.width / 2.0;
    //    [_headView addSubview:red];
    //
    //    UIView *low = [[SNShadowView alloc] init];
    //    low.frame = SNFRAME(0, 0, 15, 15);
    //    low.center = CGPointMake(sleepTypeLabel.x + 180 + FitSimpleSize(0, 10, 30, 45, 45), sleepTypeLabel.center.y);
    //    low.backgroundColor = SNHEARTSMALL;
    //    low.layer.masksToBounds = YES;
    //    low.layer.cornerRadius = low.width / 2.0;
    //    [_headView addSubview:low];
    
    //    UILabel *redLabel = [[UILabel alloc] init];
    //    redLabel.textAlignment = NSTextAlignmentLeft;
    //    redLabel.frame = SNFRAME(red.center.x + 15, red.center.y - 10, 70, 20);
    //    redLabel.textColor = SNCOLORBLACK;
    //    redLabel.text = SN_Text(@"high");
    //    redLabel.font = SNFONT(11.0);
    //    [_headView addSubview:redLabel];
    //
    //    UILabel *lowLabel = [[UILabel alloc] init];
    //    lowLabel.textAlignment = NSTextAlignmentLeft;
    //    lowLabel.frame = SNFRAME(low.center.x + 15, low.center.y - 10, 70, 20);
    //    lowLabel.textColor = SNCOLORBLACK;
    //    lowLabel.text = SN_Text(@"low");
    //    lowLabel.font = SNFONT(11.0);
    //    [_headView addSubview:lowLabel];
    
    SNShadowView *lineView_2 = [[SNShadowView alloc] init];
    [lineView_2 showWithType:1];
    CGFloat aHeight = FitSimpleSize(10, 10, 0, 0, 0);
    lineView_2.frame = SNFRAME(0, lineView_1.origin.y +65 -aHeight, HHHWIDTH, 3);
    [_headView addSubview:lineView_2];
}

- (void)loadLabelValue {
    _labelView       = [[UIView alloc] init];
    _labelView.frame = SNFRAME(0, _headView.height *0.6, HHHWIDTH, _headView.height *0.2);
    [_headView addSubview:_labelView];
    
    for (int i = 0; i < 3; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.textColor     = SNCOLORBLACK;
        unitLabel.font          = SNFONT(17.0);
        unitLabel.frame         = SNFRAME(HHHWIDTH /3 *i + 3, 13, HHHWIDTH /3, 20);
        unitLabel.tag           = 100 +i;
        [_labelView addSubview:unitLabel];
        //        [unitLabel setAttributedText:[SN_PublicClass label1With:unitLabel.text withFontsize:10.0 withChangeText1:@"bpm" withChangeText2:@"bpm"]];
    }
    
    NSArray *arrayString = [NSArray arrayWithObjects:SN_Text(@"最大值"), SN_Text(@"平均值"), SN_Text(@"最小值"), nil];
    for (int i = 0; i < 3; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.text          = arrayString[i];
        unitLabel.textColor     = SNCOLORGRAY;
        unitLabel.font          = SNSFONT(13.0);
        unitLabel.frame         = SNFRAME(HHHWIDTH /3 *i, 10 + 28, HHHWIDTH /3, 20);
        [_labelView addSubview:unitLabel];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (_tableView.height *0.35)/7.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SNOxDetailTableViewCell";
    
    SNOxDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (nil == cell) {
        cell = [[SNOxDetailTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    [cell updateOxCell:[_modelArray objectAtIndex:indexPath.row] withSelectType:_type];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)selectType:(SelectDateType)type {
    //    NSLog(@"周月年选择了>>>>>>%d",type);
    _type = type;
    OxModel        *model = [OxModel getOxModelFromDBWith:SN_PublicClass.selectDate];
    NSMutableArray *array = [NSMutableArray array];
    _modelArray = [NSMutableArray array];
    //1
    if (type == SelectDateDay) {
        for (int i = 0; i < 24 *4; i++) {
            int total = 0;
            int count = 0;
            int ave   = 0;
            for (int k = 0; k < model.oxsuArrayAuto.count; k++) {
                oxSubModel *oxmodel = [model.oxsuArrayAuto objectAtIndex:k];
                
                if (oxmodel.count == i) {
                    total += oxmodel.oxValue;
                    count++;
                }
            }
            ave = total / count;
            
            if (ave > 0) {
                [array addObject:StrByInt(ave)];
            } else {
                [array addObject:StrByInt(90)];
            }
        }
        //2
        for (int k = 0; k < model.oxsuArrayAuto.count; k++) {
            oxSubModel     *oxmodel = [model.oxsuArrayAuto objectAtIndex:k];
            NSMutableArray *arr     = [[NSMutableArray alloc] init];
            NSString       *time    = [oxmodel.updateTime componentsSeparatedByString:@" "][1];
            NSString       *value   = StrByInt(oxmodel.oxValue);
            [arr addObject:time];
            [arr addObject:value];
            [_modelArray addObject:arr];
        }
        _modelArray = (NSMutableArray *)[[_modelArray reverseObjectEnumerator] allObjects];
    } else {
        if (type == SelectDateWeek) {
            NSArray *weekArray = [NSArray arrayWithObjects:SN_Text(@"周日"), SN_Text(@"周一"), SN_Text(@"周二"), SN_Text(@"周三"), SN_Text(@"周四"), SN_Text(@"周五"), SN_Text(@"周六"), nil];
            for (int i = 0; i < 7; i++) {
                NSDate         *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:1];
                NSDate         *Date        = [first dateAfterDay:i];
                NSString       *firstString = [Date dateToDayString];
                NSString       *sss         = [NSString stringWithFormat:@"SELECT oxAve FROM OxModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString       *heartValue  = [[OxModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
                NSMutableArray *arr         = [[NSMutableArray alloc] init];
                [arr addObject:weekArray[i]];
                int heartValues = heartValue.intValue;
                [arr addObject:StrByInt(heartValues)];
                if (heartValues>0) {
                    [_modelArray addObject:arr];
                }
                if (heartValues == 0) {
                    [array addObject:StrByInt(90)];
                } else {
                    [array addObject:StrByInt(heartValues)];
                }
            }
        }
        if (type == SelectDateMonth) {
            NSInteger monthCount = [SN_PublicClass getSelectMonthDays:SN_PublicClass.selectDate];
            for (int i = 0; i < monthCount; i++) {
                NSDate         *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:2];
                NSDate         *Date        = [first dateAfterDay:i];
                NSString       *firstString = [Date dateToDayString];
                NSString       *sss         = [NSString stringWithFormat:@"SELECT oxAve FROM OxModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
                NSString       *heartValue  = [[OxModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
                NSMutableArray *arr         = [[NSMutableArray alloc] init];
                [arr addObject:firstString];
                int heartValues = heartValue.intValue;
                [arr addObject:StrByInt(heartValues)];
                
                if (heartValues > 0) {
                    [_modelArray addObject:arr];
                }
                if (heartValues == 0) {
                    [array addObject:StrByInt(90)];
                } else {
                    [array addObject:StrByInt(heartValues)];
                }
            }
            _modelArray = (NSMutableArray *)[[_modelArray reverseObjectEnumerator] allObjects];
        }
    }
    
    [_ChartView UpdateViewWithType:type withArray:array];
    [_tableView reloadData];
    [self updateValueLabel:type];
}

- (void)updateValueLabel:(SelectDateType)type {
    NSString *oxAve = @"--";
    NSString *oxMax = @"--";
    NSString *oxMin = @"--";
    
    if (_type == SelectDateDay) {
        OxModel *model = [OxModel getOxModelFromDBWith:SN_PublicClass.selectDate];
        oxAve = model.oxAve==0?@"--":[NSString stringWithFormat:@"%d %%", model.oxAve];
        oxMax = model.oxAve==0?@"--":[NSString stringWithFormat:@"%d %%", model.oxMax];
        oxMin = model.oxAve==0?@"--":[NSString stringWithFormat:@"%d %%", model.oxMin];
    } else {
        NSArray  *time = [SN_PublicClass getBeginDateStringAndEndWith:SN_PublicClass.selectDate withType:_type];
        NSString *max  = [NSString stringWithFormat:@"SELECT MAX(oxAve) AS OrderTotal FROM OxModel WHERE dateString >='%@' and dateString <='%@' and oxAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *maxs = [[OxModel getUsingLKDBHelper]executeScalarWithSQL:max arguments:nil];
        oxMax = maxs.integerValue==0?@"--":[NSString stringWithFormat:@"%d %%", maxs.intValue];
        
        NSString *min  = [NSString stringWithFormat:@"SELECT MIN(oxAve) AS OrderTotal FROM OxModel WHERE dateString >='%@' and dateString <='%@' and oxAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *mins = [[OxModel getUsingLKDBHelper]executeScalarWithSQL:min arguments:nil];
        oxMin = mins.integerValue==0?@"--":[NSString stringWithFormat:@"%d %%", mins.intValue];
        
        NSString *ave  = [NSString stringWithFormat:@"SELECT AVG(oxAve) AS OrderTotal FROM OxModel WHERE dateString >='%@' and dateString <='%@' and oxAve >0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
        NSString *aves = [[OxModel getUsingLKDBHelper]executeScalarWithSQL:ave arguments:nil];
        oxAve = aves.integerValue==0?@"--":[NSString stringWithFormat:@"%d %%", aves.intValue];
    }
    
    NSArray *array2 = [NSArray arrayWithObjects:oxMax, oxAve, oxMin, nil];
    if (array2.count > 0) {
        for (UILabel *label in _labelView.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (label.tag >= 100) {
                    label.text = array2[label.tag - 100];
                }
            }
        }
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

